<template>
  <Panel title="事件列表" class="event-list" v-bind="props.config">
    <!-- 事件类型 分类部分 :class="getClassName(item, index)" -->
    <div class="event-top">
      <div class="event-type">
        <a-tooltip
          v-for="(item, index) in typeArr"
          @click="typeClick(item, index)"
          :key="item.id"
          color="#4894ff"
          :title="getEventTypeConfig(item.name).value"
        >
          <span class="btn" :class="getClassName(item, index)">
            <a-badge :count="item.value" class="angle-num" />
            <svg-icon
              :icon-class="getEventTypeConfig(item.name).iconName"
              class="icon"
              :style="{ color: typeActive == index ? '#fff' : getEventTypeConfig(item.name).color }"
            ></svg-icon>
          </span>
        </a-tooltip>
      </div>
      <!-- <svg-icon
        icon-class="search"
        class="icon-search"
        @click="searchShow = !searchShow"
        :style="{ color: searchShow ? '#fd8419' : '' }"
      ></svg-icon> -->
    </div>

    <!-- 搜索部分 -->
    <Transition name="right">
      <div class="search" v-show="searchShow">
        <a-input class="ipt" v-model:value.trim="searchValue" allow-clear @pressEnter="search" />
        <svg-icon icon-class="search" class="search-event" @click="search"></svg-icon>
      </div>
    </Transition>

    <!-- 列表部分 -->
    <div class="scroll-list">
      <a-spin class="spin-loading" v-show="spinning" />
      <div
        class="content text-hover"
        :class="eventListActive == item.eventId ? 'content-active' : ''"
        :id="item.eventId"
        v-for="item in eventList"
        :key="item.eventId"
        @click="eventListClick(item)"
      >
        <svg-icon
          class="star-icon"
          @click.stop="starClick(item)"
          :icon-class="item.isFocus == 1 ? 'focus-on' : 'focus-not'"
        ></svg-icon>

        <span class="type">{{ getEventTypeConfig(item.eventName).value }}</span>

        <span class="describe">
          <a-tag color="blue">{{ item.happenTime ? dayjs(item.happenTime).format('MM/DD HH:mm') : '' }}</a-tag>
          <a-tag color="green">{{ item.roadNum }}</a-tag>
          <!-- <span class="road-num"> {{ item.roadNum }} </span> -->
          <span class="text">{{ item.describe }}</span>
        </span>
      </div>

      <Empty v-if="!eventList || (!eventList.length && !spinning)"></Empty>
    </div>
  </Panel>
</template>

<script>
export default {
  name: 'EventList'
}
</script>
<script setup>
/**
 * 事件列表(二级)
 * @author 阳坤（1194636148@qq.com）
 * @date   时间：2022/10/24
 */

import Panel from '../../components/panel'
import eventApi from '../../api/event.js'
import { ref, defineEmits, defineProps, watch, getCurrentInstance, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'

import dayjs from 'dayjs'
import store from '@/store'
import Empty from '../../components/empty'
import { getEventTypeConfig } from '@/core/config'

const props = defineProps({
  // 详情配置
  config: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const { proxy } = getCurrentInstance()
// 事件类型集合
const typeArr = ref([])
// 事件类型选中项
const typeActive = ref(0)
// 是否显示查询条件
const searchShow = ref(false)
// 搜索框内容
const searchValue = ref()
// 事件列表集合
const eventList = ref([])
// 第一次事件列表集合
const defalutEventList = ref([])
// 事件列表选中项
const eventListActive = ref(null)
// Loading项
const spinning = ref(false)
// emit回调方法
const emit = defineEmits(['setDetail'])
const eventTypeArr = ref({
  TAB1: '交通事故',
  TAB2: '车辆故障',
  JEB1: '施工养护',
  TBB1: '恶劣天气',
  TDB2: '障碍物',
  TDB1: '大流量',
  JGB1: '交通管制'
})
// 关注、取消关注防抖
const starTimer = ref(null)
// 搜索防抖
const searchTimer = ref(null)

// 获取事件列表定时器
const eventTimer = ref(null)

watch(
  () => (store.state.config.detailConfig.data ? store.state.config.detailConfig.data.eventId : ''),
  newValue => (eventListActive.value = newValue),
  { deep: true }
)

onMounted(() => {
  // /user/queue/talk 固定     /event/demo 订阅该topic 可随意
  // proxy.$socket.stompClient.subscribe('/user/queue/talk/event/demo', function (res) {
  //   console.log('/user/queue/talk/event/demo', '----res:')
  //   console.log(JSON.parse(res.body))
  // })
  // proxy.$socket.stompClient.subscribe('/user/queue/sys', function (res) {
  //   console.log('/user/queue/sys', '----res:' + res)
  // })
  proxy.$bus.on('eventRefresh', () => getData()) // 接受事件统计通知刷新
  getData()
})

onUnmounted(() => proxy.$bus.off('eventRefresh'))

/**
 * 获取数据
 */
const getData = (argParams, action) => {
  const params = {
    userId: store.state.user.userInfo.userId,
    province: 32,
    roadType: 1,
    eventStatus: 5,
    eventType: null
  }
  // 获取事件类型统计
  getEventTypeStatistic(params)

  const activeType = typeArr.value[typeActive.value]
  // 获取事件列表
  getEventList({
    ...params,
    eventType: activeType && activeType['name'] != 'ALL' ? activeType['name'] : null
  })
}

/**
 * 获取事件类型统计
 */
const getEventTypeStatistic = params => {
  eventApi
    .getEventTypeStatistic(params)
    .then(res => {
      if (res.data) {
        typeArr.value = res.data.statisticsModelList
      }
    })
    .catch(() => {
      message.error(`数据获取失败！`)
    })
}

/**
 * 获取事件列表
 */
const getEventList = params => {
  spinning.value = true
  eventList.value = []
  eventApi
    .getEventList(params)
    .then(res => {
      if (res.data) {
        const testArr = []
        eventList.value = res.data.map(item => {
          testArr.push(item.eventId) // 测试重复数据用
          const startStake = item.startStake ? item.startStake : ''
          const endStake = item.endStake ? '-' + item.endStake : ''
          const describe = `${startStake}${endStake} ${item.trafficInfluence} ${item.orgName}`
          const filterText = `${item.roadNum}${startStake}${endStake}${item.trafficInfluence}${item.orgName}`
          return {
            ...item,
            eventName: item.eventType,
            describe,
            filterText
          }
        })
        sortEventList()

        // 测试重复数据用
        if (new Set(testArr).size != testArr.length) console.log('有重复数据')
        else console.log('没有重复数据')
      }
    })
    .catch(() => {
      message.error(`数据获取失败！`)
    })
    .finally(() => {
      spinning.value = false
    })
}

/**
 * 事件类型点击切换
 */
const typeClick = (item, index) => {
  if (typeActive.value == index) {
    return
  }
  typeActive.value = index
  const params = {
    userId: store.state.user.userInfo.userId,
    province: 32,
    roadType: 1,
    eventStatus: 5,
    eventType: item.name == 'ALL' ? null : item.name
  }
  getEventList(params)
}

/**
 * 根据条件查询搜索
 */
const search = () => {
  if (searchTimer.value) clearTimeout(searchTimer.value)
  searchTimer.value = setTimeout(() => {
    spinning.value = true
    if (searchValue.value) {
      eventList.value = eventList.value.filter(item => {
        return item.filterText.indexOf(searchValue.value.toUpperCase()) > -1
      })
    } else {
      eventList.value = defalutEventList.value
    }
    spinning.value = false
  }, 300)
}

/**
 * 事件星标icon点击
 */
const starClick = item => {
  if (starTimer.value) clearTimeout(starTimer.value)
  starTimer.value = setTimeout(() => {
    const obj = {
      eventId: item.eventId,
      followStatus: Math.abs(item.isFocus - 1),
      userId: store.state.user.userInfo.userId
    }
    eventListActive.value = item.eventId
    eventApi
      .focusEvent(obj)
      .then(res => {
        if (res.code == 200) {
          if (item.isFocus == 1) {
            item.isFocus = 0
            // 重新排序以及定位到该关注事件
            sortEventList()
            message.success('取消关注成功')
          } else {
            item.isFocus = 1
            // 重新排序以及定位到该关注事件
            sortEventList()
            setTimeout(() => {
              if (item.eventId) document.getElementById(item.eventId).scrollIntoView()
            })
            message.success('关注成功')
          }
        } else {
          message.error('操作失败')
        }
      })
      .catch(e => {
        message.error('操作失败')
      })
  }, 200)
  // followStatus    关注状态(0:取消;1:关注)
}

/**
 * 事件列表点击
 */
const eventListClick = data => {
  // if (data.eventType == 'JGB1') return
  // const msg = {
  //   content: data,
  //   topic: '/event/demo',
  //   designee: ['admin']
  // }
  // // /app/talk 固定     /event/demo 向该topic发生信息
  // proxy.$socket.stompClient.send('/app/talk/event/demo', {}, JSON.stringify(msg))
  // proxy.$socket.stompClient.send('/app/sys', {}, JSON.stringify({ command: 'info' }))
  emit('setDetail', {
    type: 'event-list',
    actions: 'click',
    data,
    config: props.config.detailConfig
  })
}

/**
 * 处理数据、排序列表
 */
const sortEventList = () => {
  eventList.value.sort(function (a, b) {
    return new Date(b.happenTime).getTime() - new Date(a.happenTime).getTime()
  })
  const focusArr = []
  const defaultArr = []
  // 按照重点关注重新排序数据
  eventList.value.forEach(item => {
    if (item.isFocus == 1) focusArr.push(item)
    else defaultArr.push(item)
  })
  eventList.value = [...focusArr, ...defaultArr]
  defalutEventList.value = [...focusArr, ...defaultArr]
}
/**
 * 获取类名
 */
const getClassName = (item, index) => {
  const active = typeActive.value == index ? 'active' : ''
  return [active, item.name]
}

/**
 * 组件销毁前
 */
onBeforeUnmount(() => {
  if (eventTimer.value) clearInterval(eventTimer.value)
})
</script>

<style scoped lang="less">
@import url(../../styles/themes/index.less);
@import url(~@/assets/styles/transition.less);
.event-list {
  :deep(.mz-panel-content-main) {
    padding: 10px 2px;
    .event-top {
      display: flex;
      padding: 0 20px;
      justify-content: space-between;
      align-items: center;
      .event-type {
        display: flex;

        .btn.ALL {
          border: 1px solid #1172ea;
          .icon.ALL {
            background-image: url('../../assets/images/event/all-events-light.png');
            width: 19px;
            height: 14px;
          }
        }
        .btn.active.ALL {
          background: #1172ea;
          .icon.ALL {
            background-image: url('../../assets/images/event/all-events.png');
          }
        }

        .btn.JEB1 {
          border: 1px solid #06acd3;
          .icon.JEB1 {
            background-image: url('../../assets/images/event/construction-light.png');
            width: 23px;
            height: 23px;
          }
        }
        .btn.active.JEB1 {
          background: #06acd3;
          .icon.JEB1 {
            background-image: url('../../assets/images/event/construction.png');
          }
        }

        .btn.TAB1 {
          border: 1px solid #ef4821;
          .icon.TAB1 {
            background-image: url('../../assets/images/event/accident-light.png');
            width: 28px;
            height: 23px;
          }
        }
        .btn.active.TAB1 {
          background: #ef4821;
          .icon.TAB1 {
            background-image: url('../../assets/images/event/accident.png');
          }
        }

        .btn.TBB1 {
          border: 1px solid #13cad1;
          .icon.TBB1 {
            background-image: url('../../assets/images/event/bad-weather-light.png');
            width: 23px;
            height: 22px;
          }
        }
        .btn.active.TBB1 {
          background: #13cad1;
          .icon.TBB1 {
            background-image: url('../../assets/images/event/bad-weather.png');
          }
        }

        .btn.TAB2 {
          border: 1px solid #f69129;
          .icon.TAB2 {
            background-image: url('../../assets/images/event/event-gs-clgz-light.png');
            width: 24px;
            height: 18px;
          }
        }
        .btn.active.TAB2 {
          background: #f69129;
          .icon.TAB2 {
            background-image: url('../../assets/images/event/event-gs-clgz.png');
          }
        }

        .btn.TDB2 {
          border: 1px solid #f7b80f;
          .icon.TDB2 {
            background-image: url('../../assets/images/event/event-gs-zaw-light.png');
            width: 28px;
            height: 16px;
          }
        }
        .btn.active.TDB2 {
          background: #f7b80f;
          .icon.TDB2 {
            background-image: url('../../assets/images/event/event-gs-zaw.png');
          }
        }

        .btn.TDB1 {
          border: 1px solid #127bee;
          .icon.TDB1 {
            background-image: url('../../assets/images/event/event-gs-dll-light.png');
            width: 23px;
            height: 18px;
          }
        }
        .btn.active.TDB1 {
          background: #127bee;
          .icon.TDB1 {
            background-image: url('../../assets/images/event/event-gs-dll.png');
          }
        }

        .btn.JGB1 {
          border: 1px solid #127bee;
          .icon.JGB1 {
            background-image: url('../../assets/images/event/event-gs-dll-light.png');
            width: 23px;
            height: 18px;
          }
        }
        .btn.active.JGB1 {
          background: #127bee;
          .icon.JGB1 {
            background-image: url('../../assets/images/event/event-gs-dll.png');
          }
        }

        .btn {
          width: 40px;
          height: 40px;
          align-items: center;
          display: flex;
          justify-content: center;
          cursor: pointer;
          position: relative;
          transition: color 0.3s, background 0.3s, border-color 0.3s, box-shadow 0.3s;
          margin-right: 9px;
          // border-radius: 50% 50%;

          .icon {
            width: 20px;
            height: 20px;
          }

          .angle-num {
            position: absolute;
            top: 0;
            right: 4px;
            z-index: 9;
            transform: translate(50%, -50%);
            .ant-badge-count {
              background: #fd8419;
            }
          }
        }

        .active {
          background: #1172ea;
        }
      }
      .icon-search {
        width: 20px;
        height: 20px;
        cursor: pointer;
        color: rgb(65, 147, 255);
      }
    }

    .search {
      position: relative;
      padding: 10px 20px 0 20px;

      .ipt {
        background: #dbe5f7;
        border: 1px solid #b2ccff;
        border-radius: 3px;
        color: #000;
        padding-right: 40px;

        .ant-input {
          background: transparent;
        }
      }

      .search-event {
        display: inline-block;
        width: 20px;
        height: 20px;
        position: absolute;
        right: 30px;
        top: 16px;
        color: rgb(65, 147, 255);
        cursor: pointer;
        z-index: 2;
      }
    }

    .scroll-list {
      overflow: hidden;
      margin: 8px 0 0 2px;
      flex: 1;
      position: relative;

      &:hover {
        overflow: auto;
      }

      .content {
        padding: 7px 7px 7px 20px;
        word-wrap: break-word;
        word-break: break-all;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        cursor: pointer;

        &:hover {
          background: @row-hover-bg !important;
        }

        .star-icon {
          width: 16px;
          height: 16px;
          margin-bottom: 5px;
        }

        .type {
          min-width: 40px;
          margin: 0 8px;
          text-align: center;
        }

        .describe {
          font-size: 14px;
          color: #333333;

          .time {
            background: #ee5454;
            color: #fff;
            margin-right: 10px;
            padding: 0 5px;
          }
          .road-num {
            background: #f6ac07;
            margin-right: 8px;
            color: #fff;
            padding: 0 5px;
          }
          .text {
            line-height: 26px;
          }
        }
      }

      .content:nth-child(even) {
        background-color: @row-even-bg;
      }

      .content:nth-child(odd) {
        background-color: @row-odd-bg;
      }

      .content-active {
        // background: #c9d9fb;
        background: @row-active-bg !important;
      }
    }
  }
}
.text-hover:hover {
  white-space: normal !important;
}
</style>
